package com.hyd.tweet.xmpp;

import com.google.appengine.api.xmpp.JID;
import com.google.appengine.api.xmpp.Message;
import com.hyd.tweet.Application;
import com.hyd.tweet.twitter.CommandProcessor;
import com.hyd.tweet.user.User;
import com.hyd.tweet.user.UserManager;
import com.hyd.tweet.util.Cache;
import com.hyd.tweet.util.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import javax.servlet.ServletConfig;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.util.Arrays;
import java.util.List;

/**
 * 接受用户命令的 Servlet
 *
 * @author yiding.he
 */
public class XMPPServlet extends HttpServlet {

    Logger log = LoggerFactory.getLogger(XMPPServlet.class);

    @Override
    public void init(ServletConfig config) throws ServletException {
        System.out.println("Application initialized.");
    }

    @Override
    protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {

        Message xmppMessage;
        try {
            xmppMessage = XMPPUtils.getXMPP().parseMessage(req);
        } catch (IllegalArgumentException e) {
            resp.setStatus(HttpServletResponse.SC_BAD_REQUEST);
            log.error("无法解析的请求", e);
            return;
        }

        try {
            handleXMPP(xmppMessage);
        } catch (Throwable e) {
            log.error("发送消息失败", e);
        }

        resp.setStatus(HttpServletResponse.SC_OK);
    }

    private void handleXMPP(Message xmppMessage) {
        JID receiverJID = xmppMessage.getFromJid();
        List<String> messages = null;

        if (Application.getEnabled().equals("true")) {
            messages = processRequest(xmppMessage, receiverJID, messages);
        } else {
            messages = Arrays.asList(Application.getPublicNotification());
        }

        XMPPMessageSender.sendMessages(receiverJID, messages);
    }

    private List<String> processRequest(Message xmppMessage, JID receiverJID, List<String> messages) {
        try {
            String command = xmppMessage.getBody().trim();
            String account = StringUtils.getAccontFromJID(receiverJID);
            boolean isAdmin = Application.getAdministrator().equals(account);

            if (isAdmin) {
                messages = processAdminCommands(command);
            }

            if (messages == null) { // 表示没有执行管理员命令
                User user = UserManager.getUser(account);

                if (user == null) {
                    messages = Arrays.asList("您没有在机器人上注册，请通过浏览器翻墙访问 http://"
                            + Application.getAppId() + ".appspot.com 绑定您的推特帐号。");

                } else {
                    messages = CommandProcessor.process(command, user);
                }
            }

        } catch (Throwable e) {
            log.error("处理命令失败", e);
            messages = Arrays.asList("——处理命令失败: " + e.toString());
        }
        return messages;
    }

    private List<String> processAdminCommands(String command) {
        List<String> messages = null;

        if (command.equals("/clearcache")) {
            Cache.clear();
            messages = Arrays.asList("——已清空缓存。");

        } else if (command.equals("/loadusers")) {
            UserManager.preloadUsers();
            messages = Arrays.asList("——已装载用户。");

        } else if (command.equals("/pushusers")) {
            UserManager.persistentAllUsers();
            messages = Arrays.asList("——已保存用户。");

        }

        return messages;
    }
}
